#include <REGX52.H>

sbit DS1302_SCLK = P3^6;
sbit DS1302_CE = P3^5;
sbit DS1302_IO = P3^4;

//制作一个表格，反复翻手册麻烦
#define DS1302_SECOND		0x80
#define DS1302_MINUTE		0x82
#define DS1302_HOUR			0x84
#define DS1302_DATE			0x86
#define DS1302_MONTH		0x88
#define DS1302_DAY			0x8A
#define DS1302_YEAR			0x8C
#define DS1302_WP			0x8E


//定义一个数组用于设置时间     年 月 日 时 分 秒 星期
unsigned char DS1302_Time[] = {23,11,13,17,35,00,1};
//全局数组便于在不同函数中改变数组中的变量

void DS1302_Init()
{
	DS1302_CE = 0;
	DS1302_SCLK = 0;
}


void DS1302_WriteByte(unsigned char Command,Data)
{
	unsigned char i = 0; 
	DS1302_CE = 1;
	for (i = 0;i < 8;i++)
	{
		//DS1302是位-->非0即1
		DS1302_IO = Command & (0x01 << i);
		DS1302_SCLK = 1;
		DS1302_SCLK = 0;
	}
	for (i = 0;i < 8;i++)
	{
		//DS1302是位-->非0即1
		DS1302_IO = Data & (0x01 << i);
		DS1302_SCLK = 1;
		DS1302_SCLK = 0;
	}
	DS1302_CE = 0;
}


unsigned char DS1302_ReadByte(unsigned char Command)
{
	unsigned char i = 0,Data = 0x00;
	DS1302_CE = 1;
	Command |= 0x01;
	for (i = 0;i < 8;i++)
	{
		//DS1302是位-->非0即1
		DS1302_IO = Command & (0x01 << i);
		
		//DS1302_SCLK = 0;
		//DS1302_SCLK = 1;
		DS1302_SCLK = 1;
		if (7 != i)
		{
			DS1302_SCLK = 0;
		}
	}
	for (i = 0;i < 8;i++)
	{
		DS1302_SCLK = 1;
		DS1302_SCLK = 0;
		if (DS1302_IO){Data |= (0x01 << i);}
	}
	DS1302_CE = 0;
	DS1302_IO = 0;//
	return Data;
}


void DS1302_SetTime()
{
	//如果读出的时间是一个大于59且不动的数
	//则芯片可能是处于写保护状态
	//在这里加上  DS1302_WrintByte(0x8E,0x00);
	//就可以解除写保护状态
	DS1302_WriteByte(DS1302_WP,0x00);//解除写保护状态
	
	DS1302_WriteByte(DS1302_YEAR,DS1302_Time[0]/10*16+DS1302_Time[0]%10);//10进制转BBC吗 。
	DS1302_WriteByte(DS1302_MONTH,DS1302_Time[1]/10*16+DS1302_Time[1]%10);
	DS1302_WriteByte(DS1302_DATE,DS1302_Time[2]/10*16+DS1302_Time[2]%10);
	DS1302_WriteByte(DS1302_HOUR,DS1302_Time[3]/10*16+DS1302_Time[3]%10);
	DS1302_WriteByte(DS1302_MINUTE,DS1302_Time[4]/10*16+DS1302_Time[4]%10);
	DS1302_WriteByte(DS1302_SECOND,DS1302_Time[5]/10*16+DS1302_Time[5]%10);
	DS1302_WriteByte(DS1302_DAY,DS1302_Time[6]/10*16+DS1302_Time[6]%10);

	DS1302_WriteByte(DS1302_WP,0x80);//打开写保护
}


void DS1302_ReadTime()
{
	unsigned char Temp = 0;
	//年
	Temp = DS1302_ReadByte(DS1302_YEAR);
	DS1302_Time[0] = Temp/16*10+Temp%16;
	//月
	Temp = DS1302_ReadByte(DS1302_MONTH);
	DS1302_Time[1] = Temp/16*10+Temp%16;
	//日
	Temp = DS1302_ReadByte(DS1302_DATE);
	DS1302_Time[2] = Temp/16*10+Temp%16;
	//时
	Temp = DS1302_ReadByte(DS1302_HOUR);
	DS1302_Time[3] = Temp/16*10+Temp%16;
	//分
	Temp = DS1302_ReadByte(DS1302_MINUTE);	
	DS1302_Time[4] = Temp/16*10+Temp%16;
	//秒
	Temp = DS1302_ReadByte(DS1302_SECOND);	
	DS1302_Time[5] = Temp/16*10+Temp%16;
	//星期
	Temp = DS1302_ReadByte(DS1302_DAY);		
	DS1302_Time[6] = Temp/16*10+Temp%16;
}






